﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ComputerGraphics.Graphics;
using ComputerGraphics.Utils;

namespace ComputerGraphics.Geometry
{
    public class Plane : Shape
    {
        private Point3D origin;

        protected Point3D normal;

        private double d;

        public Plane(Point3D origin, Point3D normal, Texture texture)
            : base(texture)
        {
            this.origin = origin;
            this.normal = normal.Direction;

            this.d = this.normal * origin;
        }

        public Plane(Point3D origin, Point3D refA, Point3D refB, Texture texture)
            : this(origin, refA ^ refB, texture)
        {
        }

        public override Intersection Intersect(Ray r)
        {
            double t = -(normal * r.Origin - d) / normal.SquareNorm;
            Point3D p = r.Origin + normal * t;
            Point3D pp = p - r.Origin;

            double dotProduct = pp * r.Direction;

            if (MathUtils.GetZeroDouble(dotProduct) <= 0) return null;

            double dist = pp.SquareNorm / dotProduct;

            Point3D position = r.GetPointByDistance(dist);
            Point3D itsNormal = -pp.Direction;

            return new Intersection(r, this, dist, position, itsNormal);
        }

        public override Intersection InternalIntersect(Ray r)
        {
            return null;
        }
    }
}
